<?php
@session_start();
include_once("../initial.php");
$DOCUMENT_ROOT=$_SERVER["DOCUMENT_ROOT"];
include_once(constant('PROJECT_DIR')."/logic/channelLogic.php");
include_once(constant('PROJECT_DIR')."/logic/userLogic.php");
include_once(constant('PROJECT_DIR')."/logic/deviceLogic.php");
$LIST_NUMBER_PER_PAGE=10;
require_once(constant('PROJECT_DIR')."/checkLogin.php");
require_once(constant('PROJECT_DIR')."/checkAdminLogin.php");
$adminId=$_SESSION['user'];

//logic
$action="";
if(isset($_POST['action']))
{
     $action = $_POST['action'];
}
else if(isset($_GET['action']))
{
     $action=$_GET['action'];
}
//write channel
$dh = new channelLogic();
$errorInfo="";
$searchResult=array();
$searchNote="";
switch($action)
{
     case "addchannel":
         $channelInfo=array();;
         $channelInfo['name']=$_POST['name'];
         $channelInfo['info']=$_POST['info'];
        $dh->insert_channel($channelInfo);
         break;
    case "deletechannel":
        $delDevices=$_POST['channels'];
        foreach($delDevices as $did)
        {
            $dh->delete_channel($did);
        }
        break;
     case "modify":
     		$channelId=$_POST['channelid'];
     		$name=$_POST['name'];
     		$info=$_POST['info'];
     		if(trim($name)!="")
     		{
     			$dh->update_channel($channelId, $name, $info);
     		}
     		break;
     case "addTeacher":
     		$channelId=$_POST['channelId'];
     		$teacherId=$_POST['teacherid'];
     		if(!$dh->containsUser($channelId, $teacherId))
     		{
     				$dh->add_user($channelId, $teacherId);
     		}
     		break;
     case "removeChannelTeacher":
     		$channelId=$_GET['id'];
     		$teacherId=$_GET['teacherid'];
     		$dh->remove_user($channelId, $teacherId);
     		break;
     case "addDevice":
     		$channelId=$_POST['channelId'];
     		$deviceId=$_POST['deviceId'];
     		if(!$dh->containsDevice($channelId, $deviceId))
     		{
     				$dh->add_device($channelId, $deviceId);
     		}
     		break;
     case "removeChannelDevice":
     		$channelId=$_GET['id'];
     		$deviceId=$_GET['deviceId'];
     		$dh->remove_device($channelId, $deviceId);
     		break;
     case "search":
				$keyword = trim($_GET['keyword']);
    		if(strlen($keyword)<3)
    		{
    				$searchNote .="输入的关键词太短，不进行搜索,请输入长度超过3的字符串.";
    				$smarty->assign("searchNote", $searchNote);
    		}
    		//keyword长度要超过2
    		$searchResult = $dh->searchByKeyword($keyword, "limit 0,30");//默认显示
    		if(count($searchResult)==30)
    		{
    				$searchNote .="搜索词得到太多结果，只显示30条，请输入更长的搜索词";
    				$smarty->assign("searchNote", $searchNote);
    		}
    		if(count($searchResult)==0)
    		{
    				$searchNote .="没有结果，展示所有结果";
    				$smarty->assign("searchNote", $searchNote);
    		}
    		$smarty->assign("keyword", $keyword);
    		break;

}
//read channels info
$channelId="";
if(isset($_POST['id']))
{
		$channelId=$_POST['id'];
}
else if(isset($_GET['id']))
{
		$channelId=$_GET['id'];
}
if($channelId!="")
{
		$channel=$dh->get_channel(array('id'=>$channelId));
		$smarty->assign("channel", $channel[0]);
		
		//还没有在channel中的老师
		$choice="teacher";//default
		if(isset($_GET['choice']))
		{
				$choice = $_GET['choice'];
		}
		if($choice=="teacher")
		{
				$existsTeachers=$dh->get_users($channelId);
				$ul = new userLogic();
				$allTeachers = $ul->get_user(array("level"=>1));
				$teachers=array();
				$teachersExists=array();
				for($i=0; $i<count($allTeachers); $i++)
				{
						$in=false;
						for($j=0; $j<count($existsTeachers);$j++)
						{
								if($existsTeachers[$j]['uid']==$allTeachers[$i]['id'])
								{
										$in=true;
										break;
								}
						}
						if(!$in)
						{
								array_push($teachers, $allTeachers[$i]);
						}
						else
						{
								array_push($teachersExists, $allTeachers[$i]);
						}
				}
				$smarty->assign("teachers", $teachers);
				$smarty->assign("listChannelTeachers", $teachersExists);
		}
		//还没有在channel中的设备
		if($choice=="device")
		{
				$existsDevices=$dh->get_devices($channelId);
				$dl=new deviceLogic();
				$allDevices = $dl->get_device();
				$devices=array();
				$devicesExists=array();
				for($i=0; $i<count($allDevices); $i++)
				{
						$in=false;
						for($j=0; $j<count($existsDevices);$j++)
						{
								if($existsDevices[$j]['did']==$allDevices[$i]['id'])
								{
										$in=true;
										break;
								}
						}
						if(!$in)
						{
								array_push($devices, $allDevices[$i]);
						}
						else
						{
								array_push($devicesExists, $allDevices[$i]);
						}
				}
				$smarty->assign("devices", $devices);
				$smarty->assign("listChannelDevices", $devicesExists);
		}
		$smarty->assign("choice", $choice);
}


//handling the page index
$channelsNumber=0;
if(count($searchResult)>0)
{
		$channelsNumber=count($searchResult);
}
else
{
	$channelsNumber=$dh->get_channel_num();
}


$pageIndex=1;
$totalPageNumber=ceil($channelsNumber/$LIST_NUMBER_PER_PAGE);
if(isset($_GET['pageIndex']))
{
     $pageIndex=$_GET['pageIndex'];
     if($pageIndex<1 || $pageIndex > $totalPageNumber)
     {
         $pageIndex=1;
     }
}
$startItem=($pageIndex-1)*$LIST_NUMBER_PER_PAGE;
$ItemNumber=$LIST_NUMBER_PER_PAGE;

$leftPageIndex=$pageIndex<=1?1:$pageIndex-1;
$rightPageIndex=$pageIndex>=$totalPageNumber?$totalPageNumber:$pageIndex+1;
$leftMostPageIndex=$pageIndex<=5?1:$pageIndex-5;//左边显示5个页面索引
$rightMostPageIndex=$totalPageNumber<$pageIndex+5?$totalPageNumber:$pageIndex+5;//右边显示5个页面索引
$smarty->assign("leftMostPageIndex",$leftMostPageIndex);
$smarty->assign("rightMostPageIndex",$rightMostPageIndex);
$smarty->assign("leftPageIndex",$leftPageIndex);
$smarty->assign("rightPageIndex",$rightPageIndex);
$smarty->assign("pageIndex",$pageIndex);
$smarty->assign("channelsNumber", $channelsNumber);

$allchannels=array();
if(count($searchResult)>0)
{
		$allchannels=$searchResult;
}
else
{
		$allchannels=$dh->get_channel('',"order by id desc", "limit $startItem,$ItemNumber");
}
$smarty->assign("channels",$allchannels);
//handling page Index end

//list listChannelDevice
$listItem ="";
if(isset($_GET['choice']))
{
		$listItem=$_GET['choice'];
}
switch($listItem)
{
		case "teacher":
			$channelId=$_GET['id'];
			break;
		case "device":
			$channelId=$_GET['id'];
			break;
}

//list listChannelTeacher

if(strlen($errorInfo)>0)
{
     $smarty->assign("insertMessage", $errorInfo);
}
$smarty->assign("menuSelected", "channel");
$smarty->assign("projectUrl", constant('PROJECT_URL'));
$smarty->assign("currentUrl","admin/category.php");
$smarty->display("admin/channel.html");
?>
